package firstG

import groovy.json.*
import twitter4j.*
import twitter4j.conf.*;

def q =  params.get("userQuery")

def distance=800

Twitter twitter = getTwitterAuth();
Query query = new Query(q);
query.setCount(20)
GeoLocation sheffield = new GeoLocation(53.377127, -1.467705);
query.setGeoCode(sheffield, distance, Query.KILOMETERS)
QueryResult result = twitter.search(query);

def twCount =0;
System.out.println(" in twitterJSON q is " + q)

def tweetListOut = []
for (;;) {
	result = twitter.search(query);
	List <Status>tweets = result.getTweets();
	tweets.each{

		def uname = it.getUser().getScreenName()
		def lat = it?.getGeoLocation()?.getLatitude()
		def lng = it?.getGeoLocation()?.getLongitude()
		def txt =  it.getText()
		def plc = it.getPlace()?.getFullName()

		if (lat!=null)
			tweetListOut << 
			   [username: uname,
				lat: lat,  
				lng: lng,
				text: txt,
				screenname: uname
			]
	}
	query = result.nextQuery()
	if (query == null) break;
	if (twCount>30) break; 
	twCount++;
}

System.out.println(" tweets list size " + tweetListOut.size()  + " list $tweetListOut")

def json = new groovy.json.JsonBuilder(tweetListOut)
System.out.println("json $json")
println(json.toString())
 

private Twitter getTwitterAuth(){

	ConfigurationBuilder cb = new ConfigurationBuilder();
	cb.setDebugEnabled(true)
			.setOAuthConsumerKey("u59ay8TtPUn5p9VTHxdFg")
			.setOAuthConsumerSecret("LOkS2Vl9KTWXH5VMuwhb9RfIcXBXzkvyzzwD0HQtr14")
			.setOAuthAccessToken("560297710-4UmsMLOILUgIkLx6V5mdH1lbvG8ew8xvQm5YgBhY")
			.setOAuthAccessTokenSecret("mlwDtpbx9bUKTTk4wpBYVdUagGmBX6bzAYJbktoNM");
	TwitterFactory tf = new TwitterFactory(cb.build());
	//Twitter twitter = tf.getInstance();
	//Twitter twitter = tf.getSingleton()

	return tf.getInstance();
}